<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!DOCTYPE html>

<html lang="en">
	<head>
		<base href="<%=basePath%>">
<!-- 		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> -->
		<meta charset="utf-8" />
		<title>付款管理</title>
		<meta name="description" content="" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
		
		<link rel="stylesheet" href="static/ace/css/bootstrap.css" />
		<link rel="stylesheet" href="static/ace/css/font-awesome.css" />
		
		<!-- text fonts -->
		<link rel="stylesheet" href="static/ace/css/ace-fonts.css" />
		<!-- ace styles -->
		<link rel="stylesheet" href="static/ace/css/ace.css" class="ace-main-stylesheet" id="main-ace-style" />
				<link rel="stylesheet" type="text/css" href="plugins/websocketInstantMsg/ext4/resources/css/ext-all.css">
		<script type="text/javascript" src="plugins/websocketInstantMsg/ext4/ext-all-debug.js"></script>
		<script type="text/javascript" src="static/js/jquery-1.7.2.js" />
		<script type="text/javascript">
			$(top.hangge());
		</script>
	</head>
		 
	<body class="no-skin">
		<!-- /section:basics/navbar.layout -->
<!-- 		<div class="main-container" id="main-container"> -->
			
<!-- 		</div> -->
	<div id="receipt"></div>
<!-- 	<div id="receiptgrid"></div> -->
	</body>
	<script type="text/javascript">
	Ext.onReady(function () {
		
		var store = Ext.create('Ext.data.Store', {
			fields: ["payment_app_code","amount","settlement_dept","currency","receipt_amount","paymentAmount","payment_app_dept","is_income_loan","payment_app_person"],
			pageSize: 10,  //页容量5条数据
			//是否在服务端排序 （true的话，在客户端就不能排序）
			remoteSort: false,
			remoteFilter: true,
			proxy: {
				type: 'ajax',
				url: '<%=basePath%>payment/findPayment',
				reader: {   //这里的reader为数据存储组织的地方，下面的配置是为json格式的数据，例如：[{"total":50,"rows":[{"a":"3","b":"4"}]}]
					type: 'json', //返回数据类型为json格式
					root: 'result.list',  //数据
					totalProperty: 'result.total' //数据总条数
				}
			},
			sorters: [{
				property: 'ordeId',
				direction: 'desc'
			}],
			autoLoad:{start:0,limit:10},
		});
		var store1 = Ext.create('Ext.data.Store', {
			fields: ["id","payment_app_code","bill_code","invoice_code","fee_name","payment_app_dept","currency","is_cost_audit",
			         "payment_amount","early_payment","amount","remaining_balance","is_advance","is_frozen","payment_remark"
			         ],
			pageSize: 10,  //页容量5条数据
			//是否在服务端排序 （true的话，在客户端就不能排序）
			remoteSort: false,
			remoteFilter: true,
			proxy: {
				type: 'ajax',
				url: '<%=basePath%>payment/findPaymentDetail',
				reader: {   //这里的reader为数据存储组织的地方，下面的配置是为json格式的数据，例如：[{"total":50,"rows":[{"a":"3","b":"4"}]}]
					type: 'json', //返回数据类型为json格式
					root: 'result.list',  //数据
					totalProperty: 'result.total' //数据总条数
				}
			},
			sorters: [{
				property: 'ordeId',
				direction: 'desc'
			}],
			autoLoad:{start:0,limit:10},
		});
		var invoice = Ext.create('Ext.data.Store', {
			fields: ["invoice_code"],
			pageSize: 30,  //页容量5条数据
			//是否在服务端排序 （true的话，在客户端就不能排序）
			remoteSort: false,
			remoteFilter: true,
			proxy: {
				type: 'ajax',
				url: '<%=basePath%>payment/findInvoiceCodeByBillCode',
				reader: {   //这里的reader为数据存储组织的地方，下面的配置是为json格式的数据，例如：[{"total":50,"rows":[{"a":"3","b":"4"}]}]
					type: 'json', //返回数据类型为json格式
					root: 'result.list',  //数据
					totalProperty: 'result.total' //数据总条数
				}
			},
			sorters: [{
				property: 'ordeId',
				direction: 'desc'
			}],
			autoLoad: true
		});
		//托单编号数据
		var billCodeData = Ext.create('Ext.data.Store', {
				fields: ["bill_code"],
				pageSize: 30,  //页容量5条数据
				//是否在服务端排序 （true的话，在客户端就不能排序）
				remoteSort: false,
				remoteFilter: true,
				proxy: {
					type: 'ajax',
					url: '<%=basePath%>payment/findBillCodeByInvoiceCode',
					reader: {   //这里的reader为数据存储组织的地方，下面的配置是为json格式的数据，例如：[{"total":50,"rows":[{"a":"3","b":"4"}]}]
						type: 'json', //返回数据类型为json格式
						root: 'result.list',  //数据
						totalProperty: 'result.total' //数据总条数
					}
				},
				sorters: [{
					property: 'ordeId',
					direction: 'desc'
				}],
				autoLoad: true
			});
		var amount = Ext.create('Ext.data.Store', {
			fields: ["amount"],
			pageSize: 30,  //页容量5条数据
			//是否在服务端排序 （true的话，在客户端就不能排序）
			remoteSort: false,
			remoteFilter: true,
			proxy: {
				type: 'ajax',
				url: '<%=basePath%>payment/findAmountByCode',
				reader: {   //这里的reader为数据存储组织的地方，下面的配置是为json格式的数据，例如：[{"total":50,"rows":[{"a":"3","b":"4"}]}]
					type: 'json', //返回数据类型为json格式
					root: 'result.list',  //数据
					totalProperty: 'result.total' //数据总条数
				}
			},
			sorters: [{
				property: 'ordeId',
				direction: 'desc'
			}],
			autoLoad: true
		});
		  var c1 = Ext.create('Ext.container.Container', {
				layout: 'column',
				defaults: { labelAlign: 'left', labelWidth: 60 },
				items: [
					{id:"startDate1",xtype: 'textfield', name: 'startDate1',columnWidth: 1/5,padding: '5px',fieldLabel: '付款单号'},
// 					{id:"startDate2",xtype: 'textfield', name: 'startDate2', columnWidth:  1/5,padding: '5px', fieldLabel: '单位'},
// 					{id:"startDate3",xtype: 'textfield', name: 'startDate2', columnWidth:  1/5,padding: '5px', fieldLabel: '收款日期'},
// 					{id:"startDate4",xtype: 'textfield', name: 'startDate2', columnWidth:  1/5,padding: '5px', fieldLabel: '收款部门'},
					
					{xtype: "button",minWidth:70,padding: '5px',icon:'../plugins/websocketInstantMsg/ext4/shared/icons/fam/add.png', text: "查询",handler: function(){
						var payment_app_code = Ext.getCmp('startDate1').getValue();
						var store = Ext.getCmp('grid').getStore();
						store.on('beforeload', function(store,options) {  
					            var new_params = {  
					            		payment_app_code:payment_app_code
					            };  
						//这里apply一下实现新的proxy  
					            Ext.apply(store.proxy.extraParams,new_params);  
					        });  
						//对store重新载入  
					        store.load();
					}}
					]
			});
		var grid = Ext.create('Ext.grid.Panel', {
// 			renderTo: "receipt",
			store: store,
			id:'grid',
			title:"对应成本信息内容",
			height: 330,
			stripeRows:true,
			columnLines: true,
			selModel:Ext.create('Ext.selection.CheckboxModel',{mode:"single", allowDeselect: true, showHeaderCheckbox:false}),
			columns: [
				{text: 'ID', dataIndex: 'ID',hidden:true},
				{text: '付款单号', dataIndex: 'payment_app_code', align: 'left', maxWidth: 100 ,locked: true},
				{text: '单位', dataIndex: 'settlement_dept', maxWidth: 200 ,locked:true},
				{text: '付款金额', dataIndex: 'amount', maxWidth: 80},
				{text: '借款金额', dataIndex: 'paymentAmount', maxWidth: 80},
				{text: '收款金额', dataIndex: 'receipt_amount', maxWidth: 80},
				{text: '币制', dataIndex: 'currency', align: 'left', minWidth: 80},
				{text: '部门', dataIndex: 'payment_app_dept', maxWidth: 80},
				{text: '申请人', dataIndex: 'payment_app_person', maxWidth: 80},
				{text: 'is_cost_audit', dataIndex: 'is_cost_audit',hidden:true},
				{text: 'is_frozen', dataIndex: 'is_frozen',hidden:true},
				{text: 'is_submit', dataIndex: 'is_submit',hidden:true},
				{text: 'is_income_loan', dataIndex: 'is_income_loan',hidden:true}
			],
			bbar: [{
				xtype: 'pagingtoolbar',
				store: store,
				displayMsg: '显示 {0} - {1} 条，共计 {2} 条',
				emptyMsg: "没有数据",
				beforePageText: "当前页",
				afterPageText: "共{0}页",
				displayInfo: true
			}],
			listeners: {
				'itemclick': function (view, record, item, index, e) {
					var store = Ext.getCmp('receiptgrid').getStore();
					store.on('beforeload', function(store,options) {  
				            var new_params = {  
				            		payment_app_code:record.data.payment_app_code,
				            		is_income_loan:record.data.is_income_loan
				            };  

				            Ext.apply(store.proxy.extraParams,new_params);  
				        });  
				        store.load();  
				}
			},
			tbar: [
			       
			       ]
		});
		var receiptgrid = Ext.create('Ext.grid.Panel', {
// 			renderTo: "receiptgrid",
			store: store1,
			id:'receiptgrid',
			height: 330,
			title:"付款内容",
			stripeRows:true,
			columnLines: true,
			viewConfig:{
				forceFit: true,//列宽度自适应
				scrollOffset: 0//去除最右边空白

				},
			selModel:Ext.create('Ext.selection.CheckboxModel',{mode:"single", allowDeselect: true, showHeaderCheckbox:false}),
			columns: [
				{text: 'id', dataIndex: 'id',hidden:true},
				{text: '付款单号', dataIndex: 'payment_app_code', align: 'left', maxWidth: 100 ,locked: true},
				{text: '业务编号', dataIndex: 'bill_code', maxWidth: 200 ,locked:true},
				{text: '费用项目', dataIndex: 'fee_name', maxWidth: 80},
				{text: '发票号', dataIndex: 'invoice_code', maxWidth: 80},
				{text: '部门', dataIndex: 'payment_app_dept', maxWidth: 80},
				{text: '币制', dataIndex: 'currency', align: 'left', minWidth: 80},
				{text: '完税金额', dataIndex: 'payment_amount', maxWidth: 80},
				{text: '前期付款', dataIndex: 'early_payment', maxWidth: 80},
				{text: '本次付款', dataIndex: 'amount', maxWidth: 80},
				{text: '余额', dataIndex: 'remaining_balance', maxWidth: 80},
				{text: '抵冲备注', dataIndex: 'payment_remark',renderer: function(value, meta, record) {    
			         meta.attr = 'style="white-space:normal;"';     
			         return value;     
			    }  },
				{text: '是否预付', dataIndex: 'is_advance', maxWidth: 80},
				{text: '审核状态', dataIndex: 'is_cost_audit', maxWidth: 80},
				
				{text: 'is_frozen', dataIndex: 'is_frozen',hidden:true},
			],
			bbar: [{
				xtype: 'pagingtoolbar',
				store: store1,
				displayMsg: '显示 {0} - {1} 条，共计 {2} 条',
				emptyMsg: "没有数据",
				beforePageText: "当前页",
				afterPageText: "共{0}页",
				displayInfo: true
			}],
			listeners: {
				'itemclick': function (view, record, item, index, e) {
//                Ext.MessageBox.alert("标题", record.data.cataId);
				}
			},
			tbar: [{text: '付款拆分记录', icon: '../plugins/websocketInstantMsg/ext4/shared/icons/fam/table_refresh.png',handler: function(){
		    	   var records = receiptgrid.getSelectionModel().getSelection();
					var record = grid.getSelectionModel().getSelection();
		    	   
		    	   if(record[0].data.is_income_loan == 0){
		    		   Ext.Msg.alert("提示","收入只能做冲抵处理");return;
		    	   }
		    	   if(records.length==0){
		       			Ext.Msg.alert("提示","请选择需要拆分的发票");return;
		       		}
		       		if(records.length>1){
		       			Ext.Msg.alert("提示","只能拆分一张发票");return;
		       		}
		       		var win = Ext.create("Ext.window.Window", {
					    title: '拆分',
					    width: 250,
					    height: 90,
					   resizable: true,
					    modal: true,
					   closable: true,
					   maximizable: true,
					   minimizable: true,
					   closeAction :'hide',
					   items:[{

			        		xtype: 'textfield',
			        		id:'payment_amount',
			        		name: 'payment_amount',
			        		labelWidth:70,
			        		fieldLabel: '拆分金额',
			        		blankText : '拆分金额不能为空', 
			                allowBlank: false,
					   },
			        	],
					   buttons: [{
	       		            text: '拆分',
	       		            handler: function(){
	       		            	var payment_amount = Ext.getCmp('payment_amount').getValue();
// 	       		            	var payment_cost_id = Ext.getCmp('payment_cost_id').getValue();
// 	       		            	var currency = Ext.getCmp('currency').getValue();
// 	       		            	var total_amount = Ext.getCmp('total_amount').getValue();
// 	       		            	var early_payment = Ext.getCmp('early_payment').getValue();
// 	       		            	var remaining_balance = Ext.getCmp('remaining_balance').getValue();
	       		            	Ext.Ajax.request({
			       						url:'<%=basePath%>payment/savePaymentRecord',
			       						params:{
			       							payment_amount:payment_amount,
			       							payment_cost_id:records[0].data.id,
			       							currency:records[0].data.currency,
			       							total_amount:records[0].data.payment_amount,
			       							early_payment:records[0].data.early_payment,
			       							remaining_balance:records[0].data.remaining_balance
			       						},
			       						timeout:5000,
			       						success:function(response){
			       							store1.load();
			       						store.load();
			       						win.close();
			       							Ext.Msg.alert("成功","拆分成功!");
			       						},
			       						failure:function(response){
			       							store1.load();
			       							
			       						store.load();
			       						win.close();
			       							Ext.Msg.alert("错误","请求异常!");
			       						}
			       					});
	       		            }
	       		        },{
	       		            text: '关闭',
	       		            handler: function(){
	       		            	win.close();
	       		            }
	       		        }]
					});
		       	
		   	 		win.show(); 

		    	   
		       }},
// 		       {text: '预付处理', icon: '../plugins/websocketInstantMsg/ext4/shared/icons/fam/table_refresh.png',handler: function(){
// 		    	   var records = grid.getSelectionModel().getSelection();
		    	   
// 		    	   if(records.length==0){
// 		       			Ext.Msg.alert("提示","请选择需要冻结的发票");return;
// 		       		}
// 		       		if(records.length>1){
// 		       			Ext.Msg.alert("提示","只能冻结一张发票");return;
// 		       		}
// 		       }},
		       {text: '冲抵处理', icon: '../plugins/websocketInstantMsg/ext4/shared/icons/fam/table_refresh.png',handler: function(){
		    	   var records = receiptgrid.getSelectionModel().getSelection();
		    	   var record = grid.getSelectionModel().getSelection();
		    	   
		    	   if(record[0].data.is_income_loan == 1){
		    		   Ext.Msg.alert("提示","借款只能做前期付款");return;
		    	   }
		    	   if(records.length==0){
		       			Ext.Msg.alert("提示","请选择需要冲抵的发票");return;
		       		}
	       		   if(records.length>1){
	       			    Ext.Msg.alert("提示","只能冲抵一张发票");return;
	       		    }
	       		if(records[0].data.is_frozen==1){
	    		    Ext.Msg.alert("提示","已冻结，不能做冲抵处理");return;
	    	   }
		       		var win1 = Ext.create("Ext.window.Window", {
					    title: '冲抵处理',
					    width: 250,
					    height: 150,
					   resizable: true,
					    modal: true,
					   closable: true,
					   maximizable: true,
					   minimizable: true,
					   closeAction :'hide',
					   items:[{
						   xtype: 'combo',
					        typeAhead: true,
					        labelWidth:70,
					        triggerAction: 'all',
					        fieldLabel: '发票号',
					        id:'invoice_code',
					        selectOnTab: true,
					        lazyRender: true,
					        forceSelection: true,
					        editable: false,
//		 			        valueField:'amount',
					        store: invoice,
					        displayField:'invoice_code',
					        listeners: {
					            'select': function (combo,record,index) {
					            	billCodeData.on('beforeload', function(store,options) {  
		            		            var new_params = {  
		            		            		invoice_code:record[0].data.invoice_code
		            		            };  

		            		            Ext.apply(billCodeData.proxy.extraParams,new_params);  
		            		        });  
					            	billCodeData.load();  
					            	var bill_code = Ext.getCmp('bill_code').getValue();
					            	amount.on('beforeload', function(store,options) {  
		            		            var new_params = {  
		            		            		invoice_code:record[0].data.invoice_code,
		            		            		bill_code:bill_code
		            		            };  
										
		            		            Ext.apply(amount.proxy.extraParams,new_params); 
		            		            
		            		        });  
					            	amount.load({
					            			callback:function(r,options,success){  
					            				Ext.getCmp("payment_amount1").setValue(r[0].data.amount);
					            				Ext.getCmp("payment_amount2").setValue(r[0].data.amount);
					            			}
					            			});
					            },
							 
					        }
					   },{
					        xtype: 'combo',
					        typeAhead: true,
					        labelWidth:70,
					        triggerAction: 'all',
					        selectOnTab: true,
					        lazyRender: true,
					        id:'bill_code',
					        forceSelection: true,
					        fieldLabel: '业务编号',
					        editable: false,
					        store: billCodeData,
					        displayField:'bill_code',
					        
					        listeners: {
					        	  'select': function (combo,record,index) {
					        		  invoice.on('beforeload', function(store,options) {  
			            		            var new_params = {  
			            		            		bill_code:record[0].data.bill_code
			            		            };  

			            		            Ext.apply(invoice.proxy.extraParams,new_params);  
			            		        });  
					        		  invoice.load();  
					        		  
					        		  var invoice_code = Ext.getCmp('invoice_code').getValue();
						            	amount.on('beforeload', function(store,options) {  
			            		            var new_params = {  
			            		            		bill_code:record[0].data.bill_code,
			            		            		invoice_code:invoice_code
			            		            };  
											
			            		            Ext.apply(amount.proxy.extraParams,new_params); 
			            		            
			            		        });  
						            	
						            	amount.load({
					            			callback:function(r,options,success){  
					            				Ext.getCmp("payment_amount1").setValue(r[0].data.amount);
					            				Ext.getCmp("payment_amount2").setValue(r[0].data.amount);
					            			}
					            			});
						            },
					        }
					   	},{

			        		xtype: 'textfield',
			        		id:'payment_amount1',
			        		name: 'payment_amount1',
			        		labelWidth:70,
			        		fieldLabel: '金额',
			        		blankText : '金额不能为空', 
			                allowBlank: false,
// 			                listeners:{
// 			                    blur: function(){
			                    	
// 			                    	if(Ext.getCmp("payment_amount1").getValue()>Ext.getCmp("payment_amount2").getValue()){
// 			                    		Ext.Msg.alert("提示","输入金额不能大于"+Ext.getCmp("payment_amount2").getValue());
// 			                    	}
// 			                    } , 
// 			                }
					   },
					   {

			        		xtype: 'textfield',
			        		id:'payment_amount2',
			        		name: 'payment_amount2',
			        		hidden:true
					   },
			        	],
					   buttons: [{
	       		            text: '冲抵处理',
	       		            handler: function(){
	       		            	if(parseInt(Ext.getCmp("payment_amount1").getValue())>parseInt(Ext.getCmp("payment_amount2").getValue())){
			                    		Ext.Msg.alert("提示","输入金额不能大于"+Ext.getCmp("payment_amount2").getValue());
			                    		return false;
			                    	}
	       		            	if(parseInt(Ext.getCmp("payment_amount1").getValue())>parseInt(records[0].data.remaining_balance)){
	       		            		Ext.Msg.alert("提示","被抵冲发票余额还有"+parseInt(records[0].data.remaining_balance)+",输入金额不能大于"+parseInt(records[0].data.remaining_balance));
	       		            		return false;
	       		            	}
	       		            	var payment_amount = Ext.getCmp('payment_amount1').getValue();
	       		            	var bill_code = Ext.getCmp('bill_code').getValue();
	       		            	var invoice_code = Ext.getCmp('invoice_code').getValue();
	       		            	//冲抵发票的剩余金额
	       		            	var surplusAmount=parseInt(Ext.getCmp("payment_amount2").getValue())-parseInt(Ext.getCmp("payment_amount1").getValue());
	       		            	Ext.Ajax.request({
			       						url:'<%=basePath%>payment/savePaymentIntoRecord',
			       						params:{
			       							payment_amount:payment_amount,
			       							payment_cost_id:records[0].data.id,
			       							currency:records[0].data.currency,
			       							total_amount:records[0].data.payment_amount,
			       							early_payment:records[0].data.early_payment,
			       							remaining_balance:records[0].data.remaining_balance,
			       							invoice_code:invoice_code,
			       							bill_code:bill_code,
			       							surplusAmount:surplusAmount
			       						},
			       						timeout:5000,
			       						success:function(response){
			       							store1.load();
			       						store.load();
			       						win1.close();
			       							Ext.Msg.alert("成功","冲抵成功!");
			       						},
			       						failure:function(response){
			       							store1.load();
			       							
			       						store.load();
			       						win1.close();
			       							Ext.Msg.alert("错误","请求异常!");
			       						}
			       					});
	       		            }
	       		        },{
	       		            text: '关闭',
	       		            handler: function(){
	       		            	win1.close();
	       		            }
	       		        }]
					});
		       	
		   	 		win1.show(); 

		       }},]
		});
		 var panel = new Ext.Panel({
	            frame: true,
// 	            layout:"form",
// 	            width: 260,
// 	            height: 130,
// 	            labelWidth: 70,
	            title: "审核",
	            renderTo:"receipt",
	            items:[c1,grid,receiptgrid],

	            
	        });
	});
	</script>
</html>